package com.jdjc.wx.handler;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 工厂类
 */
@Component // 将类标记为Spring组件
@Slf4j     // 启用Lombok自动生成日志实例
public class WxChatMsgFactory implements InitializingBean {

    @Resource // 注入WxChatMsgHandler实现类的列表
    private List<WxChatMsgHandler> wxChatMsgHandlerList;

    private Map<WeChatMsgTypeEnum, WxChatMsgHandler> handlerMap = new HashMap<>();

    // 根据消息类型获取对应的处理器
    public WxChatMsgHandler getHandlerByMsgType(String msgType) {
        WeChatMsgTypeEnum msgTypeEnum = WeChatMsgTypeEnum.getByMsgType(msgType);
        return handlerMap.get(msgTypeEnum);
    }

    @Override // 覆盖InitializingBean接口的afterPropertiesSet方法
    public void afterPropertiesSet() throws Exception {
        for (WxChatMsgHandler wxChatMsgHandler : wxChatMsgHandlerList) {
            handlerMap.put(wxChatMsgHandler.getMsgType(), wxChatMsgHandler);
        }
    }
}
